﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Microhard.Framework.MVCHelper
{
    public class ScriptGridSearchButton : BaseButton
    {
        private string _onGridDataBindingName;

        public Dictionary<string, string> SearchFieldNames { set; get; }

        public ScriptGridSearchButton(string OnGridDataBindingName)
        {
            this._onGridDataBindingName = OnGridDataBindingName;
            this._assetKey = SysConst.OPERATION_SEARCH;
        }

        public override System.Web.Mvc.MvcHtmlString WriteHtml(System.Web.Mvc.HtmlHelper helper, string linkText, string actionName, string controllerName)
        {
            return base.CreateButton(SysConst.OPERATION_SEARCH, helper, this._id, linkText, false, null, null, null);
        }

        public override string WriteJQueryReadyInnerScript()
        {
            StringBuilder searchClick = new StringBuilder();
            searchClick.Append("$('#" + this._id + "').click(function(){");
            searchClick.Append("var grid = $('#" + this._gridID + "').data('tGrid');");
            searchClick.Append("grid.currentPage = 1;");
            searchClick.Append("grid.ajaxRequest();");
            searchClick.Append("return false;");
            searchClick.Append("});");

            return searchClick.ToString();
        }

        public override string WriteJQueryReadyOutterScript()
        {
            //构造查询script
            StringBuilder script = new StringBuilder();
            StringBuilder parms = new StringBuilder();
            script.AppendLine("function " + _onGridDataBindingName + "(e){");
            //构造取值与构造赋值
            foreach (var m in SearchFieldNames)
            {
                script.Append("var " + m.Value + " = $('#" + m.Value + "').val();");
                parms.Append("'" + m.Key + "':" + m.Value + ",");
            }
            string strParms = parms.ToString();
            strParms = strParms.Remove(strParms.Length - 1, 1);
            script.Append(" var model = { " + strParms + " };e.data = model;");
            script.Append("}");
            return script.ToString();
        }
    }
}
